package com.lagou.edu.utils;


import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;


public class AnnotationUtils {

    /**
     * 从物理路径反射具体的类集合
     *
     * @param directory   物理路径
     * @param packageName 包名
     * @return 类集合
     * @throws ClassNotFoundException 异常
     */
    public static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException {
        List<Class> classes = new ArrayList<>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
//        Preconditions.checkNotNull(files, directory + "路径无任何文件或文件夹");
        for (File file : files) {
            if (file.isDirectory()) {
                //递归查找文件夹【即对应的包】下面的所有文件
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + '.' + file.getName()));
            } else if (file.getName().endsWith(".class")) {
                classes.add(Class.forName(packageName + "." + file.getName().substring(0, file.getName().length() - 6)));
            }
        }
        return classes;
    }


    /**
     * 从一个包中查找出所有类,在jar包中不能查找
     *
     * @param packageName 包名
     * @return 结果类集合
     * @throws IOException            io异常
     * @throws ClassNotFoundException 找不到类异常
     */
    public static List<Class> getClassesByPackageName(String packageName) throws IOException, ClassNotFoundException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(resource.getFile()));
        }
        ArrayList<Class> classes = new ArrayList<>();
        for (File directory : dirs) {
            classes.addAll(findClasses(directory, packageName));
        }
        return classes;
    }


    public static void main(String[] args) throws Exception {
        // 获取目标类包名（可替换为死的包名路径）
        String packageName = "com.lagou.edu";
        List<Class> classesByPackageName = getClassesByPackageName(packageName);
        System.out.println("classesByPackageName = " + classesByPackageName);
    }
}
